package red.mlz.module.module.material.service;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import red.mlz.module.module.category.mapper.CategoryMapper;
import red.mlz.module.module.material.entity.Material;
import red.mlz.module.module.material.mapper.MaterialMapper;
import red.mlz.module.module.material.request.MaterialContentDto;
import red.mlz.module.module.tag.entity.MaterialsTagsRelation;
import red.mlz.module.module.tag.entity.Tag;
import red.mlz.module.module.tag.mapper.MaterialsTagsRelationMapper;
import red.mlz.module.module.tag.mapper.TagMapper;
import red.mlz.module.module.tag.service.TagService;
import red.mlz.module.module.user.service.BaseUserService;
import red.mlz.module.utils.BaseUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MaterialService {
    @Resource
    private MaterialMapper mapper;
    @Resource
    private TagService tagService;
    @Resource
    private MaterialsTagsRelationMapper materialsTagsRelationMapper;


    public Material getById(BigInteger id) {
        return mapper.getById(id);
    }

    public Material extractById(BigInteger id) {
        return mapper.extractById(id);
    }

    public void insert(Material Material) {
        mapper.insert(Material);
    }

    public int update(Material Material) {
        return mapper.update(Material);
    }

    public void delete(BigInteger id) {
        mapper.delete(id, BaseUtils.currentSeconds());
    }


//    public List<Material> getMaterialsForConsole(int page, int pageSize, String title) {
//        int begin = (page - 1) * pageSize;
//        return mapper.getMaterialsForConsole(begin, pageSize, "desc", title);
//    }
//
//    public int getMaterialsTotalForConsole(String title) {
//        return mapper.getMaterialsTotalForConsole(title);
//    }
//
//
//    // for app list
//    // key  can be  Material title
//    // or key can be username
//    public List<Material> getMaterialList(int page, int pageSize, String key) {
//        int begin = (page - 1) * pageSize;
//        String userIds = null;
//        if (!BaseUtils.isEmpty(key)) {
//            userIds = baseUserService.getUserIdsForSearch(key);
//        }
//        return mapper.getMaterialList(begin, pageSize, key, userIds);
//    }
//
//
//    public List<Material> getAll(int page, int pageSize) {
//        int begin = (page - 1) * pageSize;
//        return mapper.getAll(begin, pageSize);
//    }


    @Transactional
    public BigInteger editMaterial(BigInteger materialId, String name, BigInteger categoryId, String productName, Integer materialCount, String imageUrls, String content, String tags) {
        try {
            // 修改的内容
            List<MaterialContentDto> checkContents = JSON.parseArray(content, MaterialContentDto.class);
            for (MaterialContentDto checkContent : checkContents) {
                if (!MaterialDefine.isMaterialContentType(checkContent.getType())) {
                    throw new RuntimeException("Material content is error");
                }
            }
        } catch (Exception cause) {
            // ignores
            throw new RuntimeException("Material content is error");
        }
        if (BaseUtils.isEmpty(name) || BaseUtils.isEmpty(imageUrls)) {
            throw new RuntimeException("Material name or coverImage is error");
        }

        Material material = new Material();
        material.setName(name);
        material.setCategoryId(categoryId);
        material.setProductName(productName);
        material.setMaterialCount(materialCount);
        material.setImageUrls(imageUrls);
        material.setContent(content);
        material.setIsDeleted(0);

        if (BaseUtils.isEmpty(materialId)) {
            material.setCreateTime(BaseUtils.currentSeconds());
            insert(material);
        } else {
            Material old = getById(materialId);
            if (BaseUtils.isEmpty(old)) {
                throw new RuntimeException("edit article error, old not exist");
            }
            material.setId(materialId);
            update(material);
        }

        // 标签业务
        if (!BaseUtils.isEmpty(tags)) {
            List<Tag> tagList = tagService.insertBatch(tags);
            List<MaterialsTagsRelation> materialsTagsRelationList = tagList.stream()
                    .map(tag -> {
                        MaterialsTagsRelation materialsTagsRelation = new MaterialsTagsRelation();
                        materialsTagsRelation.setMaterialId(material.getId());
                        materialsTagsRelation.setTagId(tag.getId());
                        materialsTagsRelation.setUpdateTime(BaseUtils.currentSeconds());
                        materialsTagsRelation.setCreateTime(BaseUtils.currentSeconds());
                        materialsTagsRelation.setIsDeleted(0);
                        return materialsTagsRelation;
                    }).collect(Collectors.toList());
            materialsTagsRelationMapper.deleteByMaterialId(material.getId());
            materialsTagsRelationMapper.insertBatch(materialsTagsRelationList);
        }
        return material.getId();
    }


    public List<Material> getMaterialsForConsole(int page, int pageSize, String keyword, String categoryIds) {
        int begin = (page - 1) * pageSize;
        return mapper.getMaterialList(begin, pageSize, "desc", keyword, categoryIds);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        MaterialContentDto materialContentDto = new MaterialContentDto();
        materialContentDto.setType("text");
        materialContentDto.setContent("特别好的材料");
        MaterialContentDto materialContentDto1 = new MaterialContentDto();
        materialContentDto1.setType("image");
        materialContentDto1.setContent("https://sky-take-out-0426.oss-cn-beijing.aliyuncs.com/image/2503/31/94d56e16c5e64cc4aefeedbaa17e626e_812×375.png");
        List<MaterialContentDto> checkContents = new ArrayList<>();
        checkContents.add(materialContentDto);
        checkContents.add(materialContentDto1);
        String jsonString = JSON.toJSONString(checkContents);
        String encode = URLEncoder.encode(jsonString, "utf8");

        System.out.println(encode);
    }

    public int getMaterialsTotalForConsole(String keyword, String categoryIds) {
        return mapper.getMaterialsTotalForConsole(keyword, categoryIds);
    }

    public List<Material> getMaterialList(int page, int pageSize, String keyword, String categoryIds) {
        int begin = (page - 1) * pageSize;
        return mapper.getMaterialList(begin, pageSize, "desc", keyword, categoryIds);
    }
}
